<?php

class Cron {

    public static function updateSchedules() {

        $dbo = DBO::getInstance();

        $dbo->query('SELECT mtl.update_schedules()');
    }

    public static function doTasks($count = 10) {

        $dbo = DBO::getInstance();

        $tasks = $dbo->getAll('SELECT * FROM sys.tasks WHERE NOT completed ORDER BY id ASC LIMIT ?', array(DBInteger::create($count)), DB_FETCHMODE_ASSOC);

        foreach($tasks as $task) {

            $status = TASK_FAILED;

            switch($task['task']) {

                case 'notify_leaked':

                    $status = Task::notifyLeaked(DBInteger::create($task['user_id']), DBInteger::create($task['param_int']));
                    //$status = TASK_INVALID;
                    break;

                case 'notify_release':

                    $status = Task::notifyRelease(DBInteger::create($task['user_id']), DBInteger::create($task['param_int']));
                    break;

                case 'notify_artist':

                    $status = Task::notifyArtist(DBInteger::create($task['user_id']), DBInteger::create($task['param_int']));
                    break;

                case 'notify_unleaked':

                    $status = TASK_INVALID;
                    break;
            }

            switch($status) {

                case TASK_OK:
                    $dbo->query('UPDATE sys.tasks SET completed = TRUE, time_completed = NOW() WHERE id = ?', array(DBInteger::create($task['id'])));
                    break;

                case TASK_FAILED:
                    // TODO: logging
                    break;

                case TASK_INVALID:
                    // TODO: logging
                    $dbo->query('DELETE FROM sys.tasks WHERE id = ?', array(DBInteger::create($task['id'])));
                    break;
            }

        }
    }


}